<template>
  <div>
    <my-header :showBack="true" title="我的帮余额交易"></my-header>
    <div class="trade_info">
      <section class="my_assets">
        <label for="">
          <span>可用帮余额</span>
          <span style="color:#4b0">{{Math.floor(indexData.useMoney*100)/100||0}}</span>
        </label>
         <label for="">
          <span>交易帮余额</span>
          <span style="color:#4b0">{{Math.floor(indexData.lockMoney*100)/100||0}}</span>
        </label>
      </section>
      <van-tabs v-model="active">
        <van-tab title="我的求购">
          <ul class="my_trade_info" v-if="tradeInfo.moneyNum">
            <li>
              <label for="">求购时间：{{tradeInfo.createTime | formatDate}}</label>
            </li>
            <li>
              <label for="">求购数量：{{tradeInfo.moneyNum}}</label>
            </li>
            <li>
              <label for="">总价(￥)：{{tradeInfo.moneyNum}}</label>
            </li>
            <li>
              <van-button type="danger" style="margin-top:50px;" size="large" @click="cancleMyTradeById">取消求购</van-button>
            </li>
          </ul>
          <div class="no_data" v-else>
            {{$t("lang.NoData")}}
          </div>
        </van-tab>
        <van-tab title="我的出售">
           <ul class="my_trade_info" v-if="tradeInfo.moneyNum">
            <li>
              <label for="">出售时间：{{tradeInfo.createTime | formatDate}}</label>
            </li>
            <li>
              <label for="">出售数量：{{tradeInfo.moneyNum}}</label>
            </li>
            <li>
              <label for="">总价(￥)：{{tradeInfo.moneyNum}}</label>
            </li>
            <li>
              <van-button type="danger" style="margin-top:50px;" size="large" @click="cancleMyTradeById">取消出售</van-button>
            </li>
          </ul>
          <div class="no_data" v-else>
            {{$t("lang.NoData")}}
          </div>
        </van-tab>
        <van-tab title="交易中">
          <div v-if="tradingInfo.moneyNum">
            <ul class="my_trading_info">
              <li>交易状态：<i style="color:#f44">{{tradingInfo.tradeStatus==2?'待支付':'待确认'}}</i></li>
              <li>交易数量：{{tradingInfo.moneyNum}}</li>
              <li>交易总价(￥)：{{Math.floor(tradingInfo.moneyNum*100)/100}}</li>
            </ul>
            <!-- 如果自己是买家就显示自己的信息 或者 交易审核完成状态 买卖双方都显示 -->
            <div v-if="tradingInfo.flagMerchant == 0||tradingInfo.applyStatus == 2"> 
              <div class="trading_title">买家信息</div>
              <ul class="my_trading_info">
                <li>真实姓名：{{tradingInfo.buyRealName}}</li>
                <li>电话号码：{{tradingInfo.buyCustomerPhone}}</li>
                <li>支付宝号：{{tradingInfo.buyCustomerAlipay}}</li>
                <li>开户银行：{{tradingInfo.buyBankName}}</li>
                <li>银行卡号：{{tradingInfo.buyBankCard}}</li>
              </ul>
            </div>
            <!-- 如果自己是卖家就显示自己的信息 或者 交易审核完成状态 买卖双方都显示 -->
            <div v-if="tradingInfo.flagMerchant == 1||tradingInfo.applyStatus == 2"> 
              <div class="trading_title">卖家信息</div>
              <ul class="my_trading_info">
                <li>真实姓名：{{tradingInfo.mallRealName}}</li>
                <li>电话号码：{{tradingInfo.mallCustomerPhone}}</li>
                <li>支付宝号：{{tradingInfo.mallCustomerAlipay}}</li>
                <li>开户银行：{{tradingInfo.mallBankName}}</li>
                <li>银行卡号：{{tradingInfo.mallBankCard}}</li>
              </ul>
            </div>
            
            <div v-if="tradingInfo.voucherImg&&tradingInfo.voucherImg.length>0"> 
              <div class="trading_title">付款凭证</div>
              <ul class="my_trading_info trading_img_box" >
                <li @click="showTradingImg(tradingInfo.voucherImg,0)">
                  <img :src="tradingInfo.voucherImg[0]" alt="">
                </li>
                <li @click="showTradingImg(tradingInfo.voucherImg,1)">
                  <img :src="tradingInfo.voucherImg[1]" alt="">
                </li>
              </ul>
            </div>

            <div class="trading_btn">
              <!-- 如果未审核 买卖家都显示取消交易 -->
              <van-button type="danger" size="large" v-if="tradingInfo.applyStatus==1" @click="cencelTrade">取消交易</van-button>
              <!-- 如果审核通过 买家显示上传凭证 -->
              <van-button type="primary" size="large" v-if="tradingInfo.applyStatus==2&&tradingInfo.tradeStatus==2&&tradingInfo.flagMerchant==0" @click="showUploadPopup">上传凭证</van-button>
              <!-- 如果审核通过 卖家显示确认收款 -->
              <van-button type="primary" size="large" v-if="tradingInfo.applyStatus==2&&tradingInfo.tradeStatus==3&&tradingInfo.flagMerchant==1" @click="confirmMyTrade">确认收款</van-button>

              <!-- <van-button type="danger" size="large">投诉</van-button> -->
            </div>

            <van-popup v-model="uploadPopup" position="bottom" class="upload_popup" @click-overlay="goBack">
              <div class="upload_popup_box">
                <label for="" @click="showBigImg(1)" >
                  <!-- <img src="../../assets/img/home/paymentScreenshot1.jpg" alt="" srcset=""> -->
                </label>
                <label for="" @click="showBigImg(2)">
                  <!-- <img src="../../assets/img/home/paymentScreenshot2.jpg" alt="" srcset=""> -->
                </label>
                <label for="uploadImg1">
                  <img src="" alt="" srcset="" ref="img1">
                  <i style="font-size:50px;" v-show="files1" class="iconfont icon-upload-img"></i>
                  <input type="file" @change="addImg(1)" accept="image/jpeg,image/jpg,image/png" ref="fileInfo1" id="uploadImg1" />
                </label>
                <label for="uploadImg2">
                  <img src="" alt="" srcset="" ref="img2">
                  <i style="font-size:50px;" v-show="files2" class="iconfont icon-upload-img"></i>
                  <input type="file" @change="addImg(2)" accept="image/jpeg,image/jpg,image/png" ref="fileInfo2" id="uploadImg2"/>
                </label>
              </div>
              <div class="footer_btn">
                <van-button type="primary" size="large" @click="confirmUpload">立即上传</van-button>
              </div>
            </van-popup>
          </div>
          
          <div class="no_data" v-else>
            {{$t("lang.NoData")}}
          </div>
        </van-tab>
        <van-tab title="已完成">
          <ul>
            <van-list v-if="completeTrade.length>0" v-model="loading" :finished="finished" @load="loadMore" :offset="10">
              <li v-for="(item,index) in completeTrade" class="complete_trade">
                <label for=""  @click="showTradeDetails(item,index)">
                  <span>{{item.tradeMatchTime | formatDate}}</span>
                  <span class="complete_name">{{item.flagMerchant==0?item.mallRealName:item.buyRealName}}</span>
                  <i class="iconfont icon-arrow-right" v-show="!item.isShowDetails"></i>
                  <i class="iconfont icon-arrow-down" v-show="item.isShowDetails"></i>
                </label>
                <div v-show="item.isShowDetails" style="margin: 2%;">
                  <div class="trading_title">交易信息</div>
                  <ul class="my_trading_info">
                    <li>交易状态：{{item.tradeStatus==6?'交易成功':'交易失败'}}</li>
                    <li>交易类型：{{item.flagMerchant==0?'购买':'出售'}}</li>
                    <li>交易数量：{{item.moneyNum}}</li>
                    <li>交易总价(￥)：{{Math.floor(item.moneyNum*100)/100}}</li>
                  </ul>
                  <!-- 如果自己是买家就显示自己的信息 或者 交易审核完成状态 买卖双方都显示 -->
                  <div v-if="item.flagMerchant == 1&&item.tradeStatus==6"> 
                    <div class="complete_title">买家信息</div>
                    <ul class="my_trading_info">
                      <li>真实姓名：{{item.buyRealName}}</li>
                      <li>电话号码：{{item.buyCustomerPhone}}</li>
                      <li>支付宝号：{{item.buyCustomerAlipay}}</li>
                      <li>开户银行：{{item.buyBankName}}</li>
                      <li>银行卡号：{{item.buyBankCard}}</li>
                    </ul>
                  </div>
                  <!-- 如果自己是卖家就显示自己的信息 或者 交易审核完成状态 买卖双方都显示 -->
                  <div v-if="item.flagMerchant == 0&&item.tradeStatus==6"> 
                    <div class="complete_title">卖家信息</div>
                    <ul class="my_trading_info">
                      <li>真实姓名：{{item.mallRealName}}</li>
                      <li>电话号码：{{item.mallCustomerPhone}}</li>
                      <li>支付宝号：{{item.mallCustomerAlipay}}</li>
                      <li>开户银行：{{item.mallBankName}}</li>
                      <li>银行卡号：{{item.mallBankCard}}</li>
                    </ul>
                  </div>
                  <div v-if="item.voucherImg"> 
                    <div class="complete_title">付款凭证</div>
                    <ul class="my_trading_info trading_img_box" >
                      <li @click="showTradingImg(item.voucherImg,0)">
                        <img :src="item.voucherImg[0]" alt="">
                      </li>
                      <li @click="showTradingImg(item.voucherImg,1)">
                        <img :src="item.voucherImg[1]" alt="">
                      </li>
                    </ul>
                  </div>
                </div>
              </li>
            </van-list>
            <div class="no_data" v-else>{{$t("lang.NoData")}}</div>
          </ul>
        </van-tab>
      </van-tabs>
      
    </div>
  </div>
</template>

<script>
import header from "@/components/header";
import timeFormat from "../../store/timeFormat";
import $ from "jquery";
import { Indicator,MessageBox } from "mint-ui";
import { Toast,ImagePreview  } from "vant";

export default {
  components: {
    "my-header": header
  },
  data(){
    return{
      active:'',
      indexData: {},
      tradeInfo: {},
      tradingInfo:{},
      uploadPopup:false,
      files1:'',
      files2:'',

      completeTrade:[],
      loading:false,
      finished:true,
      searchData:{
        pageNo:1,
        pageSize:30,
      }
    }
  },
  filters: {
    formatDate(time) {
      var date = new Date(time);
      return timeFormat.formatDate(date, "yyyy.MM.dd hh:mm:ss");
    }
  },
  watch:{
    '$route'(val,oldval){
      //处理物理键返回关闭messageBox      
      if(oldval.fullPath.indexOf('?')!=-1){
        if(this.uploadPopup){
          this.uploadPopup = false;
        }
        MessageBox.close(false);
      }
    },
    active(val,oldval){
      if(val==0){
        this.selectMyTrade(2);
      }else if(val==1){
        this.selectMyTrade(1);
      }else if(val==2){
        this.selectMyTrading();
      }else{
        this.getCompleteTrade();
      }
    }
  },
  created(){
    if(this.$route.fullPath.indexOf('?')!=-1){
      this.goBack();
    }
  },
  mounted(){
    this.getIndexData();
    this.active = parseInt(this.$route.params.type);
  },
  methods:{
    getIndexData() {
      this.$ajax(this.$api.selectIndexData).then(res => {
        if (res.code == 0) {
          this.indexData = res.data;
        }
      });
    },
    //查询我的求购出售
    selectMyTrade(type) {
      this.$ajax(this.$api.selectMyTrade,{type:type}).then(
      res => {
        if (res.code == 0) {
          if(res.data&&res.data.length>0){
            this.tradeInfo = res.data[0];
          }else{
            this.tradeInfo = {}
          }
        }
      });
    },
    //取消我的求购出售
    cancleMyTradeById(){
      //处理物理键返回关闭messageBox
      if(window.location.href.indexOf('?MessageBox')==-1){
        window.location.href = window.location.href+'?MessageBox';
      }
      MessageBox({message:'确认取消'+(this.active==0?'求购？':'出售？'),closeOnClickModal:false,showCancelButton:true}).then(action => {
        if(action=='confirm'){
          this.$ajax(this.$api.cancleMyTradeById,{id:this.tradeInfo.id}).then(
          res => {
            if (res.code == 0) {
              Toast({ message: "取消成功", position: "bottom" });
              this.selectMyTrade(this.active==0?2:1);
              this.getIndexData();
            }
          });
          this.goBack();
        }else{
          this.goBack();
        }
      }).catch(() => {});
    },

    //查询交易中数据
    selectMyTrading(){
      this.$ajax(this.$api.selectMyTrading).then(
      res => {
        if (res.code == 0) {
          if(res.data&&res.data.length>0){
            this.tradingInfo = res.data[0];
          }else{
            this.tradingInfo = {}
          }
        }
      });
    },

    cencelTrade(){
      //处理物理键返回关闭messageBox
      if(window.location.href.indexOf('?MessageBox')==-1){
        window.location.href = window.location.href+'?MessageBox';
      }
      MessageBox({message:'确认取消交易？',closeOnClickModal:false,showCancelButton:true}).then(action => {
        if(action=='confirm'){
          this.$ajax(this.$api.cancleMyTradeById,{id:this.tradingInfo.id}).then(
          res => {
            if (res.code == 0) {
              Toast({ message: "取消成功", position: "bottom" });
              this.selectMyTrading();
              this.getIndexData();
            }
          });
          this.goBack();
        }else{
          this.goBack();
        }
      }).catch(() => {});
    },

    showUploadPopup(){
      //处理物理键返回关闭popup
      if (window.location.href.indexOf("?uploadPopup") == -1) {
        window.location.href = window.location.href + "?uploadPopup";
      }
      this.uploadPopup = true;
    },
    //建立一個可存取到該file的url
    getObjectURL(file) {
      let url = null;
      if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    addImg(id) {
      if (id == 1) {
        var fileInfo1 = this.$refs.fileInfo1.files[0];
        if(fileInfo1){
          let objUrl = this.getObjectURL(fileInfo1);
          // this.imgArr[0] = objUrl;
          this.files1=fileInfo1;
          this.$refs.img1.src = objUrl;
        }
      } else if (id == 2) {
        var fileInfo2 = this.$refs.fileInfo2.files[0];
        if(fileInfo2){
          let objUrl = this.getObjectURL(fileInfo2);
          // this.imgArr[1] = objUrl;
          this.files2=fileInfo2;
          this.$refs.img2.src = objUrl;
        }
      }
    },
    showBigImg(num){
      if(num==1){
        ImagePreview([require('../../assets/img/home/paymentScreenshot1.jpg')]);
      }else{
        ImagePreview([require('../../assets/img/home/paymentScreenshot2.jpg')]);
      }
    },
    showTradingImg(voucherImg,num){
      ImagePreview(voucherImg, num);
    },
    confirmUpload(){
      if(!this.files1||!this.files2){
        Toast({ message: '请一次上传两张图片', position: "bottom" });
        return;
      }
      const vm = this;
      var formData = new FormData();
      formData.append('files',this.files1);
      formData.append('files',this.files2);
      formData.append('id',this.tradingInfo.id)
      formData.append('token',localStorage.getItem('token'))
      Indicator.open({
        spinnerType: "fading-circle"  
      });
      $.ajax({
        url: vm.$api.baseURL + vm.$api.payMyTrade.url,
        type: "post",
        data: formData,
        //十分重要，不能省略
        cache: false,
        processData: false,
        contentType: false,
        success: function(res) {
          if (res.code == 0) {
            Toast({ message: '上传成功', position: "bottom" });
            vm.selectMyTrading();
            vm.getIndexData();
            vm.uploadPopup = false;
          } else if (res.code == 1) {
            Toast({ message: res.msg, position: "bottom" });
          } else if (res.code == 2) {
            Toast({ message: res.msg, position: "bottom" });
            vm.$router.push({
              path: "/login"
            });
          }
          vm.goBack();
          Indicator.close();
        },
        error: function(e) {
          vm.goBack();
          Indicator.close();
          console.log(e);
        }
      });
    },

    //确认收款
    confirmMyTrade(){
      this.$ajax(this.$api.confirmMyTrade,{id:this.tradingInfo.id}).then(
      res => {
        if (res.code == 0) {
          Toast({ message: '操作成功', position: "bottom" });
          this.selectMyTrading();
          this.getIndexData();          
        }
      });
    },

    //初始获取已完成列表
    getCompleteTrade(){
      this.searchData.pageNo = 1;
      this.$ajax(this.$api.selectMyTradeList, this.searchData).then(res => {
        if (res.code == 0) {
          if (res.data && res.data.list.length > 0) {
              this.loading = false;
              res.data.list.forEach(function(item){
                item.isShowDetails = false;
              });
              this.completeTrade = res.data.list;
              this.finished = this.searchData.pageNo == res.data.pageCount;
          } else {
            this.completeTrade = [];
          }
        }
      });
    },
    loadMore(){
      this.searchData.pageNo += 1;
      this.$ajax(this.$api.selectMyTradeList, this.searchData).then(res => {
        if (res.code == 0) {
          if (res.data && res.data.list) {
            res.data.list.forEach(function(item){
              item.isShowDetails = false;
            });
            this.loading = false;
            this.completeTrade = this.completeTrade.concat(res.data.list);
            this.finished = this.searchData.pageNo == res.data.pageCount;
          }
        }
      });
    },
    showTradeDetails(data,key){
      this.$nextTick(function () {
        this.completeTrade.forEach(function(item,index){
          if(key == index){
            item.isShowDetails = !item.isShowDetails;
          }else{
            item.isShowDetails = false;
          }
        });
      })
    },
  }
}
</script>

<style scoped>
.trade_info{
  background: #f5f5f5;
}
.my_assets {
  margin: 10px 2% 5px;
  display: flex;
  justify-content: space-between;
  background: #fff;
  box-shadow: 3px 3px 3px 1px #f2f2f2;
}
.my_assets label {
  width: 50%;
  box-sizing: border-box;
  margin: 5px 0;
  line-height: 20px;
  border-right: 1px #eee solid;  
}
.my_assets label:last-child{
  border-right:none;
}
.my_assets span {
  display: block;
  text-align: center;
  font-size: 12px;
  color: #666;

}

.my_trade_info{
  padding: 10px 2%;
  line-height: 36px;
  background: #fff;
  color: #666;
}
.my_trading_info{
  padding: 10px 2%;
  line-height: 36px;
  background: #fff;
  color: #666;
  /* border-bottom: 1px #eee solid; */
}
.trading_img_box{
  display: flex;
  justify-content: space-between;
}
.trading_img_box li{
  width: 48%;
  margin: 0 1%;
  flex: 1;
}
.trading_title{
  padding: 10px 2%;
  /* border-top: 1px #eee solid; */
  border-bottom: 1px #eee solid;
  background: #fff;
  margin-top: 10px;
}

.trading_btn{
  margin:20px 2%;
}
.trading_btn button{
  margin-top: 10px;
}
.upload_popup{
  width: 100%;
  padding: 20px 0;
}
.upload_popup_box{
  display: flex;
  margin-bottom: 65px;
}
.upload_popup_box label{
  flex: 1;
  width: 22.5%;
  margin-left: 2%;
  padding: 2px;
  border: 1px #ccc solid;
  border-radius: 2px;
  box-sizing: border-box;
  background: #fff;
  text-align: center;
  height: 150px;
  line-height: 140px;
}
.upload_popup_box label:last-child{
  margin-right: 2%;
}
.upload_popup_box img{
  width: auto;
  max-width: 100%;
  max-height: 100%;
  
}
.upload_popup_box input{
  display: none;
}
.complete_trade {
  background: #fff;
 
}
.complete_trade label{
  line-height: 44px;
  display: flex;
  margin: 0 2%;
  border-bottom: 1px #eee solid;
}
.complete_trade label>span{
  flex: 1;
  padding: 0 5px;
}
.complete_name{
  text-align: right;
}
.complete_title{
  padding: 10px 2%;
  border-bottom: 1px #eee solid;
  background: #fff;
}
.complete_trade .my_trading_info{
  border-bottom: 1px #eee solid;
}
</style>
